from datetime import datetime
from types import SimpleNamespace

import happybase

def convert_date_to_number(time_date):
    # 根据指定的日期时间格式解析字符串为日期时间对象
    datetime_obj = datetime.strptime(time_date, "%Y/%m/%d")
    year = datetime_obj.year
    month = datetime_obj.month
    day = datetime_obj.day
    numeric_date = year * 10000 + month * 100 + day

    return numeric_date


connection = happybase.Connection('192.168.139.136')
table_name = 'hot_search'
table = connection.table(table_name)

request_data = {
    "start_date": "2024/1/12",
    "end_date": "",
    "platform": 1,
    "highest_rank": 2,
    "hot_content": ""
}
request_data = SimpleNamespace(**request_data)
# 构造查询条件
start_date = request_data.start_date
end_date = request_data.end_date
platform = request_data.platform
highest_rank = request_data.highest_rank
hot_content = request_data.hot_content

if start_date:
    start_date = convert_date_to_number(start_date)
if end_date:
    end_date = convert_date_to_number(end_date)

filter_str = ""

if start_date:
    filter_str += f"SingleColumnValueFilter('cf', 'date_number', >=, 'binary:{str(start_date)}')"
if end_date:
    if filter_str:
        filter_str += " AND "
    filter_str += f"SingleColumnValueFilter('cf', 'date_number', <=, 'binary:{str(end_date)}')"
if highest_rank is not None and highest_rank != 0:
    if filter_str:
        filter_str += " AND "
    filter_str += f"SingleColumnValueFilter('cf', 'highest_rank', =, 'binary:{str(highest_rank)}')"
if hot_content:
    if filter_str:
        filter_str += " AND "
    filter_str += f"SingleColumnValueFilter('cf', 'hot_content', =, 'binary:{str(hot_content)}')"

if platform is not None and platform != 0:
    if filter_str:
        filter_str += " AND "
    filter_str += f"SingleColumnValueFilter('cf', 'platform', =, 'binary:{str(platform)}')"

# print(filter_str)
# 执行查询
# scan = table.scan(filter=filter_str)

# 定义模糊查询的模式
string = '拜登特朗普双双胜出'
byte_string = string.encode('utf-8')

# 执行模糊查询
scan_kwargs = {
    'filter': "SingleColumnValueFilter('cf', 'column', >=, 'regexstring:.*{}.*')".format(byte_string.decode('utf-8')),
    'columns': ['cf:hot_content']  # 要检索的列族和列名
}

scan = table.scan(**scan_kwargs)

# 获取查询结果
results = []
for key, data in scan:
    row_key = key.decode()
    row_data = {column.decode(): value.decode() for column, value in data.items()}
    results.append((row_key, row_data))

# 打印查询结果
for row_key, row_data in results:
    print(f"Row Key: {row_key}")
    for column, value in row_data.items():
        print(f"{column}: {value}")
    print()

# 关闭连接
connection.close()